#include "Thread.hpp"

Thread::Thread()
:_pthread_id(0)
,_isRunning(false)
{}

Thread::~Thread(){}

void Thread::start(){
    if(!_isRunning){
        int result = pthread_create(&_pthread_id, nullptr, start_routine, this);
        if(result != 0){
            fprintf(stderr, "%s", strerror(result));
            return;
        }
        _isRunning = true;
    }
}

void* Thread::start_routine(void *arg){
    // 形成多态（基类指针指向派生类对象）
    Thread *pthread = static_cast<Thread *>(arg);
    if(pthread){
        pthread->run();
    }
    return nullptr;
}

void Thread::join(){
    if(_isRunning){
        pthread_join(_pthread_id, nullptr);
        _isRunning = false;
    }
}